import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroupFile;

public class ASTViz {

    public ASTViz(Tree tree) {
        this.root = tree;
        templates = new STGroupFile(Tools.getResourcePath("DOT.stg"));
    }

    private Tree root;
    private STGroupFile templates;

    private int count = 0;

    @Override
    public String toString() {
        count = 0;

        var fileST = templates.getInstanceOf("file");
        fileST.add("gname", "testgraph");

        var nodeST = templates.getInstanceOf("node");

        // 加入根节点
        count = 1;
        nodeST.add("name", "node1");
        nodeST.add("label", root.payload);
        fileST.add("nodes", nodeST.render());

        // 遍历子节点
        WalkChildren(root, fileST);
        return fileST.render();
    }


    private void WalkChildren(Tree tree, ST fileST) {
        var parentIndex = count;

        for (var child : tree.children) {

            var nodeST = templates.getInstanceOf("node"); // 每次都会创建新的 StringTemplate 对象
            var edgeST = templates.getInstanceOf("edge");
            
            count++;
            nodeST.add("name", "node" + count);
            nodeST.add("label", child.payload);

            edgeST.add("from", "node" + parentIndex);
            edgeST.add("to", "node" + count);

            fileST.add("nodes", nodeST.render());
            fileST.add("edges", edgeST.render());
            
            if (tree.getChildCount() > 0) {
                WalkChildren(child, fileST);
            }
        }
    }
}
